﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq.Dynamic.Core;
using System.Windows.Forms.VisualStyles;

namespace Dotnet.FormExtensions.UsrControl
{
    public partial class UcDataGridViewGroup : UserControl
    {
        private DataTable _orginalDataTable = new DataTable();//原始数据
        private DataTable _groupSumDataTable=new DataTable();//分组汇总数据
        private event EventHandler<EventArgs> _checkboxStateChange = null;
        private List<string> _groupSumColumns=new List<string>();
        public UcDataGridViewGroup()
        {
            InitializeComponent();
            dgvMain.RowPostPaint += DgvMain_RowPostPaint;
        }

        public event EventHandler<EventArgs> CheckBoxStateChange
        {
            add { _checkboxStateChange += value; }
            remove { _checkboxStateChange -= value; }
        }
        protected void OnCheckBoxStateChange(EventArgs e)
        {
            var temp=System.Threading.Volatile.Read(ref _checkboxStateChange);
            if (temp != null)
            {
                temp(this, e);
            }
        }

        private void DgvMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X + 1, e.RowBounds.Location.Y, dgvMain.RowHeadersWidth - 2, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgvMain.RowHeadersDefaultCellStyle.Font, rectangle,
                Color.Red, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        public List<string> GroupSumColumns
        {
            set { _groupSumColumns = value; }
        }
        public DataTable DataSource
        {
            get { return _orginalDataTable; }
            set
            {
                if (value != null)
                {
                    _orginalDataTable = value;
                    InitCheckbox(_orginalDataTable);
                }
            }
        }
        public void Clear()
        {
            dgvMain.DataSource = null;
        }

        public DataTable GroupSumDataTable { get => _groupSumDataTable; set => _groupSumDataTable = value; }

        private void InitCheckbox(DataTable dt)
        {
            panChk.Controls.Clear();
            int i = 0;
            foreach (DataColumn col in dt.Columns)
            {
                CheckBox chk = GetCheckbox(i,col);
                i++;
                this.panChk.Controls.Add(chk);  
            }
            dgvMain.DataSource = null;
            _groupSumDataTable = GetDynamicGroupBySum(dt, _groupSumColumns.ToArray());
            dgvMain.DataSource = _groupSumDataTable;
        }
        private CheckBox GetCheckbox(int idx,DataColumn col)
        {
            CheckBox chk=new CheckBox();
            if(_groupSumColumns.Contains(col.ColumnName)) chk.Checked=true;
            else  chk.Checked = false;
            chk.AutoSize = true;
            chk.Location = new System.Drawing.Point(10, 20*idx);
            chk.Margin = new System.Windows.Forms.Padding(4, 4, 40, 4);
            chk.Name = col.ColumnName;
            chk.Size = new System.Drawing.Size(120, 30);
            chk.TabIndex = idx+1;
            chk.Text = col.ColumnName;
            chk.UseVisualStyleBackColor = true;
            chk.CheckStateChanged += Chk_CheckStateChanged;
            return chk;
        }
        private void Chk_CheckStateChanged(object sender, EventArgs e)
        {
            CheckBox chk=sender as CheckBox; 
            if (chk.Checked) {
                _groupSumColumns.Add(chk.Name);
            }
            else
            {
                _groupSumColumns.Remove(chk.Name);
            }
            _groupSumDataTable = GetDynamicGroupBySum(_orginalDataTable, _groupSumColumns.ToArray());
            dgvMain.DataSource = null;
            dgvMain.DataSource = _groupSumDataTable;
            OnCheckBoxStateChange(e);
        }

        private DataTable GetDynamicGroupBySum(DataTable dt, params string[] columns)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string str in columns)
            {
                sb.Append(str).Append(",");
            }
            DataTable dtSum = dt.Clone().DefaultView.ToTable(true, columns);

            if (columns.Length == 0) dtSum.Columns.Clear();
            if (dtSum.Columns.Contains("汇总") == false)
            {
                dtSum.Columns.Add("汇总", typeof(System.String));
            }
            if (dtSum.Columns.Contains("总") == false)
            {
                dtSum.Columns.Add("总", typeof(System.Decimal));
            }
            if (dtSum.Columns.Contains("条数") == false)
            {
                dtSum.Columns.Add("条数", typeof(System.Int32));
            }
            var groupByStr = $" new ({sb.ToString().TrimEnd(',')}) ";
            var selector = "new ( Sum(Convert.ToDecimal(it.金额)) as 汇总,Count() as 条数,it.Key)";
            var query = dt.AsEnumerable().AsQueryable().GroupBy(groupByStr).Select(selector);
            var groupList = query.ToDynamicList();
            foreach (var item in groupList)
            {
                DataRow dr = dtSum.NewRow();
                foreach (string key in columns)
                {
                    dr[key] = item.Key[key];
                }
                dr["汇总"] = string.Format("{0:N2}", item.汇总);
                dr["总"] = item.汇总;
                dr["条数"] = item.条数;
                dtSum.Rows.Add(dr);
            }
            DataTable dtSum1=dtSum.AsEnumerable().OrderByDescending(t=>t.Field<int>("条数")).CopyToDataTable();
            return dtSum1;
        }
    }
}
